<?php

namespace backend\modules\orders\controllers;

use backend\modules\base\controllers\BaseController;
use backend\modules\marketing\models\ShareReb;
use backend\modules\orders\models\ShareRebUser;
use common\models\Wxuser;
use Yii;
use backend\modules\orders\models\OrderGoods;
use backend\modules\orders\models\search\OrderGoodsSearch;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * OrdergoodsController implements the CRUD actions for OrderGoods model.
 */
class OrdergoodsController extends BaseController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['rebdetail' ,'index','sort','create','view','update','del','getrebinfo','paytoper'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all OrderGoods models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new OrderGoodsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single OrderGoods model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new OrderGoods model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new OrderGoods();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->rec_id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing OrderGoods model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->rec_id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing OrderGoods model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * 用户返利列表
     * @return string
     */
    public function actionGetrebinfo()
    {
        $shareRebUserARR = ShareRebUser::find()
            ->select('sru.* ,u.wx_name,u.wx_images ')
            ->from('share_reb_user AS sru')
            ->leftJoin('user AS u','sru.user_id = u.id')
            ->asArray()
            ->All();
        return $this->render('index',['shareRebUserARR'=>$shareRebUserARR]);
    }

    /**
     * 用户返利详情
     * @return string
     */
    public function actionRebdetail()
    {
        $info['wx_name'] = $_GET['wx_name'];
        $info['wx_images'] = $_GET['wx_images'];
        $share_reb_user_id = $_GET['share_reb_user_id'];
        $user_id = ShareRebUser::findOne($share_reb_user_id)->user_id;
        $shareRebARR = ShareReb::find()
            ->select('sr.* ,g.goods_image,g.goods_name,u.wx_name as buyer_name,u.wx_images as buyer_images,oi.order_sn ')
            ->from('share_reb AS sr')
            ->leftJoin('goods AS g','sr.goods_id = g.goods_id')
            ->leftJoin('user AS u','sr.buyer_id = u.id')
            ->leftJoin('order_info AS oi','sr.order_id = oi.order_id')
            ->where(['sr.user_id'=>$user_id])
            ->asArray()->all();
        return $this->render('rebdetail',['info'=>$info,'shareRebARR'=>$shareRebARR]);
    }

    /**
     * 企业支付
     * @return string
     */
    public function actionPaytoper()
    {
        $userid = isset($_POST['userid'])?$_POST['userid']:'';
        $reb_money =  isset($_POST['reb_money'])?$_POST['reb_money']:'';
        $token =  isset($_POST['token'])?$_POST['token']:'';
        $srid =  isset($_POST['srid'])?$_POST['srid']:'';

        if($token !== '@pooai@789456') {
            return json_encode([false,'密文错误']);
        }
        if(!$token&&!$userid&&!$reb_money&!$srid){
            return json_encode([false,'数据错误']);
        }


        $shareBeb = ShareReb::findOne($srid);
        if( $shareBeb->is_payed ==1){
            return json_encode([false,'已经支付过！']);
        }
        $shareBeb->is_payed = 1;
        if(!$shareBeb->save()){
            print_r($shareBeb->errors);exit;
        }

        $info['openid'] = Wxuser::findOne($userid)->openid;
//        $info['reb_money'] = $reb_money;
        $info['reb_money'] = 200;
        $info['check'] = '@pooai@123456';
        $url = Yii::$app->params['domurl']."wxpay/example/toper.php";
        $post_data = $info;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        curl_close($ch);

        return json_encode([true,'']);
    }

    /**
     * Finds the OrderGoods model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return OrderGoods the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = OrderGoods::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
